﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace GingerBeard.Utilities
{
	public static class XmlParser
	{
		public delegate Node ProcessNodeDelegate(XmlReader r, Node parent);

		public class NodeRecord
		{
			public NodeRecord(String inName, ProcessNodeDelegate inProcessDelegate)
			{
				name = inName;
				processDelegate = inProcessDelegate;
			}

			String name;
			public System.String Name
			{
				get { return name; }
				set { name = value; }
			}
			ProcessNodeDelegate processDelegate;
			public ProcessNodeDelegate ProcessDelegate
			{
				get { return processDelegate; }
				set { processDelegate = value; }
			}
		}

		public static Node LoadNode(XmlReader r, Node parent, NodeRecord[] nodeRecords)
		{
			Node newNode = null;

			while (r.Read())
			{
				if (r.NodeType == XmlNodeType.Element)
				{
					foreach (NodeRecord nodeRecord in nodeRecords)
					{
						if (nodeRecord.Name == r.Name.ToLower())
						{
							String currentNodeName = r.Name;
							String xml = r.ReadOuterXml();
							XmlReaderSettings settings = new XmlReaderSettings();
							settings.ConformanceLevel = ConformanceLevel.Fragment;
							XmlReader childReader = XmlReader.Create(new StringReader(xml), settings);
							childReader.ReadToFollowing(currentNodeName); 
							newNode = nodeRecord.ProcessDelegate(childReader, parent);

							if (parent != null)
								parent.Nodes.Add(newNode);

							childReader = XmlReader.Create(new StringReader(xml), settings);
							childReader.ReadToFollowing(currentNodeName);
							LoadNode(childReader, newNode, nodeRecords);
							break;
						}
					}
				}
			}

			return newNode;
		}
	}
}
